package Cn.edu.zafu.bigdata.x.cxy;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileOperations {

    // 写入文件的方法
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("内容已写入文件：" + fileName);
        } catch (IOException e) {
            System.out.println("写入文件时发生错误：" + e.getMessage());
        }
    }

    // 读取文件的方法
    public static void readFromFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到：" + e.getMessage());
        } catch (IOException e) {
            System.out.println("读取文件时发生错误：" + e.getMessage());
        }
    }

    // 主方法，用于测试
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文本内容：");
        String content = scanner.nextLine();
        scanner.close();

        // 获取当前Java文件所在的目录
        String currentDir = new File("").getAbsolutePath();
        // 构建files目录的路径
        String filesDir = currentDir + File.separator + "files";

        // 创建files目录如果它不存在
        File directory = new File(filesDir);
        if (!directory.exists()) {
            directory.mkdirs();
            System.out.println("已创建files目录");
        }

        // 构建文件的路径
        String fileName = filesDir + File.separator + "202203090119.txt";

        // 将输入的文本写入文件
        writeToFile(fileName, content);

        // 读取文件内容并打印
        readFromFile(fileName);
    }
}